package com.mezz.bones.im.logic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.framework.core.strategy.StrategyContext;
import com.mezz.bones.im.common.enums.ActionCodeEnum;
import com.mezz.bones.im.common.event.MessageReceivedEvent;
import com.mezz.bones.im.common.event.MessageSendWithConnectEvent;
import com.mezz.bones.im.common.exception.ImBaseException;
import com.mezz.bones.im.common.message.base.Message;
import com.mezz.bones.im.common.message.base.MessageHeader;
import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.common.process.IMessageProcessor;
import com.mezz.bones.im.common.result.ImResultCode;
import com.mezz.bones.im.logic.process.interfaces.MessageLogicProcess;
import com.mezz.bones.im.logic.service.IMessageReceiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: zhuang
 * @Date: 2025/2/5 11:13
 * @Description: TODO
 * @Version: 1.0
 **/

@Service
@Slf4j
public class MessageReceiveServiceImpl implements IMessageReceiveService {
    @Resource
    private StrategyContext strategyContext;

    @Resource
    private IMessageProcessor messagePublisher;
    @Override
    public Object handleMessage(MessageReceivedEvent event) {

        Message message = event.getImMessage();
        MessageHeader header = message.getHeader();
        String actionCode = header.getActionCode();
        ImUserConnectInfo senderUserConnectInfo = event.getImUserInfo();
        log.debug("im service receive message: {}", JSONObject.toJSONString(message));

        MessageLogicProcess messageLogicProcess = strategyContext.getStrategy(MessageLogicProcess.class, message.getHeader().getActionCode());

        try {
            return messageLogicProcess.handler(senderUserConnectInfo, message.getHeader(), message.getBody());
        } catch (ImBaseException e) {
            log.error("handleMessageReceive ImBaseException error",e);
            ImResultCode resultCode = e.getResultCode();
            messagePublisher.sendMessage2UserConnect(new MessageSendWithConnectEvent(header.getTraceId(), actionCode, e.getMessage(), senderUserConnectInfo, resultCode));
            throw e;
        } catch (Exception e) {
            log.error("handleMessageReceive Exception error",e);
            //业务异常 发送异常消息到发送者客户端
            messagePublisher.sendMessage2UserConnect(new MessageSendWithConnectEvent(header.getTraceId(), actionCode, e.getMessage(), senderUserConnectInfo,ImResultCode.SYS_ERROR));
            throw e;
        }
    }
}
